package com.maxwell.googleplay.manager;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author yue
 * @创建时间 2016-3-30下午5:55:51
 * @描述 创建线程池，执行任务，提交任务
 * 
 */
public class ThreadPoolProxy {

	int mCorePoolSize;
	int mMaximumPoolSize;
	long mKeepAliveTime;

	public ThreadPoolProxy(int corePoolSize, int maximumPoolSize,
			long keepAliveTime) {
		super();
		mCorePoolSize = corePoolSize;
		mMaximumPoolSize = maximumPoolSize;
		mKeepAliveTime = keepAliveTime;
	}

	ThreadPoolExecutor mExecutor;// 只需创建一次

	/***** 初始化线程池，保证有且仅有一个实例 ******/
	private ThreadPoolExecutor initThreadPoolExecutor() {//双重检查加锁
		if (mExecutor == null) {
			synchronized (ThreadPoolProxy.class) {
				if (mExecutor == null) {
					TimeUnit unit = TimeUnit.MILLISECONDS;
					BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();// 无解队列
					ThreadFactory threadFactory = Executors
							.defaultThreadFactory();
					RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
					mExecutor = new ThreadPoolExecutor(mCorePoolSize,// 核心线程数
							mMaximumPoolSize, // 最大的线程数
							mKeepAliveTime, // 保持时间
							unit, // 保持时间对应的单位
							workQueue, // 缓存队列或者阻塞队列
							threadFactory,//
							handler);
				}
			}

		}
		return mExecutor;
	}

	/**** 执行任务 ******/
	public void execute(Runnable task) {
		initThreadPoolExecutor();
		mExecutor.execute(task);
	}

	/**** 提交任务 ******/
	public Future<?> submit(Runnable task) {
		initThreadPoolExecutor();
		return mExecutor.submit(task);
	}

	/**** 移除任务 ******/
	public void remove(Runnable task) {
		initThreadPoolExecutor();
		mExecutor.remove(task);
	}
}
